<template>
  <div class="container">
    <div class="top-bar">
      <div class="upload-section">
          <el-button size="small" type="primary" :disabled="!well_id" @click="showImportDialog = true">点击上传</el-button>
          <div v-if="!well_id" style="color: #f56c6c; font-size: 12px; margin-top: 5px;">请先选择井</div>
        <!-- 导入文件对话框 -->
        <el-dialog
            title="导入分层数据"
            :visible.sync="showImportDialog"
            :width="dialogWidth"
            :close-on-click-modal="false"
            @close="cancelImport"
        >
          <!-- 上传区域 -->
          <el-upload
              ref="upload"
              :auto-upload="false"
              :on-change="handleFileChange"
              :show-file-list="true"
              :file-list="excelFileList"
              accept=".xlsx,.xls"
              action=""
              drag
              v-if="!showDataPreview"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              拖拽Excel文件到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              支持上传 .xlsx, .xls 格式文件
            </div>
            <el-button
                type="primary"
                @click.stop="parseExcelFile"
                :disabled="!hasFile"
                style="margin-top: 15px;"
            >
              解析文件
            </el-button>
          </el-upload>

          <!-- 加载状态 -->
          <div v-if="loading" class="loading-container">
            <i class="el-icon-loading"></i>
            <p>正在解析Excel文件，请稍候...</p>
          </div>

          <!-- 数据预览和字段选择区域 -->
          <div v-if="showDataPreview" class="preview-container">
            <div class="field-selection">
              <el-checkbox
                  v-model="selectAllFields"
                  :indeterminate="isIndeterminate"
                  @change="handleSelectAll"
              >
                全选字段
              </el-checkbox>

              <el-checkbox-group
                  v-model="selectedFields"
                  @change="handleFieldChange"
                  class="fields-group"
              >
                <el-checkbox
                    v-for="field in allFields"
                    :label="field"
                    :key="field"
                >
                  {{ field }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <!-- 预览数据信息 -->
            <div class="preview-info">
              共 {{ previewData.length }} 条数据，当前显示
              {{ (previewCurrentPage - 1) * previewPageSize + 1 }} -
              {{ Math.min(previewCurrentPage * previewPageSize, previewData.length) }} 条
            </div>

            <el-table
                :data="paginatedPreviewData"
                border
                height="400"
                style="width: 100%; margin-top: 15px;"
            >
              <el-table-column
                  v-for="field in allFields"
                  :prop="field"
                  :label="field"
                  :key="field"
                  :show-overflow-tooltip="true"
              ></el-table-column>
            </el-table>
            <!--预览数据分页-->
            <el-pagination
                v-if="previewData.length > previewPageSize"
                layout="prev, pager, next"
                :current-page="previewCurrentPage"
                :page-size="previewPageSize"
                :total="previewData.length"
                @current-change="handlePreviewPageChange"
                style="margin-top: 15px; text-align: center;"
            >
            </el-pagination>
          </div>

          <!-- 对话框底部按钮 -->
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancelImport">取消</el-button>
            <el-button
                type="primary"
                @click="confirmImport"
                :disabled="!canImport"
            >
              确认导入
            </el-button>
          </div>
        </el-dialog>
      </div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="demo-ruleForm">
        <!--  下拉框，显示井的数据-->
        <el-form-item label="选择井" prop="wellName">
          <!--这个井是个下拉框，下拉框的内容从后端获取-->
          <el-select v-model="well_id" placeholder="请选择井名称" @change="handleChange">
            <el-option
                v-for="item in wellList"
                :key="item.id"
                :label="item.well_name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <!--一个数据预处理的按钮，点击后，会调用后端的方法，对数据进行预处理-->
      <el-button type="primary" style="margin-top:-25px;" @click="handleData()">数据预处理</el-button>
    </div>
    <!--  导入文件 -->
    <!--  表格部分，动态显示显示导入的文件里面的表头和数据 -->
    <div class="table-container">
      <el-table v-if="well_id" :data="fileList" style="width: 100%" height="550">
        <el-table-column label="序号" width="80">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="name" align="center">
        <el-table-column prop="name" label="地层名称" align="center" width="80">
        </el-table-column>
        </el-table-column>
        <el-table-column label="top_depth" align="center">
        <el-table-column prop="top_depth" label="顶深" width="90" align="center">
          <template slot-scope="scope">
            <span :class="getCellClass(scope.row.top_depth)">
            {{ scope.row.top_depth }}
            </span>
          </template>
        </el-table-column>
        </el-table-column>
        <el-table-column label="bottom_depth" align="center">
        <el-table-column prop="bottom_depth" label="底深" width="120" align="center">
          <template slot-scope="scope">
            <span :class="getCellClass(scope.row.bottom_depth)">
            {{ scope.row.bottom_depth }}
            </span>
          </template>
        </el-table-column>
        </el-table-column>
        <el-table-column label="thickness" align="center">
        <el-table-column prop="thickness" label="层厚度" align="center"/>
        </el-table-column>
        <el-table-column label="vertical_top_depth" align="center">
        <el-table-column prop="vertical_top_depth" label="顶深垂深" width="200" align="center"/>
        </el-table-column>
        <el-table-column label="vertical_bottom_depth" align="center">
        <el-table-column prop="vertical_bottom_depth" label="底深垂深" width="220" align="center"/>
        </el-table-column>
        <el-table-column label="vertical_thickness" align="center">
        <el-table-column prop="vertical_thickness" label="层垂厚" align="center" width="200"/>
        </el-table-column>
        <el-table-column label="plan_actual" align="center">
        <el-table-column prop="plan_actual" label="设计实际判别码" align="center"/>
        </el-table-column>
        <el-table-column label="level" align="center">
        <el-table-column prop="level" label="地层级别" align="center"/>
        </el-table-column>
        <el-table-column label="remark" align="center">
        <el-table-column prop="remark" label="备注" align="center"/>
        </el-table-column>
      </el-table>
    </div>
    <!--    分页组件 -->
    <MyPagination :currentPage="currentPage" :pageSize="pageSize" :total="total" @newValue="handleSizeChange"
                  @newCurrentPage="handleCurrentChange"/>
  </div>
</template>
<script>

import {defineComponent} from "vue";
import MyPagination from "@/components/MyPagination.vue";
import api from "@/api/api";

export default defineComponent({
  components: {MyPagination},
  data() {
    return {
      originalData: {},//原始数据
      previewCurrentPage: 1,//数据预览当前页
      previewPageSize: 50, // 每页显示50条数据
      showImportDialog: false,//是否显示导入弹窗
      dialogWidth: '60%',//弹窗宽度
      excelFile: null,//上传的excel文件
      loading: false,//是否正在加载
      excelFileList: [],//上传的excel文件列表
      showDataPreview: false,//是否显示数据预览
      allFields: [], // 所有字段
      previewData: [], // 预览数据
      totalRecords: 0, // 总记录数
      selectedFields: [], // 选中的字段
      selectAllFields: false, // 是否全选字段
      isIndeterminate: false, // 半选状态
      fileList: [
        {"name": '韩江组', "top_depth": 917, "bottom_depth": 1569, "thickness": '', "vertical_top_depth": '', "vertical_bottom_depth": '', "vertical_thickness": '', "plan_actual": '实际', "level": '', "remark": ''},
        {"name": '韩江组', "top_depth": 917, "bottom_depth": 1569, "thickness": '', "vertical_top_depth": '', "vertical_bottom_depth": '', "vertical_thickness": '', "plan_actual": '实际', "level": '', "remark": ''},
        {"name": '韩江组', "top_depth": 917, "bottom_depth": 1569, "thickness": '', "vertical_top_depth": '', "vertical_bottom_depth": '', "vertical_thickness": '', "plan_actual": '实际', "level": '', "remark": ''},
        {"name": '韩江组', "top_depth": 917, "bottom_depth": 1569, "thickness": '', "vertical_top_depth": '', "vertical_bottom_depth": '', "vertical_thickness": '', "plan_actual": '实际', "level": '', "remark": ''},
        {"name": '韩江组', "top_depth": 917, "bottom_depth": 1569, "thickness": '', "vertical_top_depth": '', "vertical_bottom_depth": '', "vertical_thickness": '', "plan_actual": '实际', "level": '', "remark": ''},
        {"name": '韩江组', "top_depth": 917, "bottom_depth": 1569, "thickness": '', "vertical_top_depth": '', "vertical_bottom_depth": '', "vertical_thickness": '', "plan_actual": '实际', "level": '', "remark": ''},
        {"name": '韩江组', "top_depth": 917, "bottom_depth": 1569, "thickness": '', "vertical_top_depth": '', "vertical_bottom_depth": '', "vertical_thickness": '', "plan_actual": '实际', "level": '', "remark": ''},
        {"name": '韩江组', "top_depth": 917, "bottom_depth": 1569, "thickness": '', "vertical_top_depth": '', "vertical_bottom_depth": '', "vertical_thickness": '', "plan_actual": '实际', "level": '', "remark": ''},
        {"name": '韩江组', "top_depth": 917, "bottom_depth": 1569, "thickness": '', "vertical_top_depth": '', "vertical_bottom_depth": '', "vertical_thickness": '', "plan_actual": '实际', "level": '', "remark": ''},
        {"name": '韩江组', "top_depth": 917, "bottom_depth": 1569, "thickness": '', "vertical_top_depth": '', "vertical_bottom_depth": '', "vertical_thickness": '', "plan_actual": '实际', "level": '', "remark": ''},
      ],
      well_id: '井3(示例井)',
      wellList: [],
      //   制定规则
      form: {
        wellName: '',
      },
      //分页查询参数
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示条数
      total: 0, // 数据总条数
      rules: {
        wellName: [
          {required: true, message: '请选择井名称', trigger: 'blur'}
        ],
      },
    }
  },
  computed: {
    // 分页后的预览数据
    paginatedPreviewData() {
      if (!this.previewData || this.previewData.length === 0) return []

      const start = (this.previewCurrentPage - 1) * this.previewPageSize
      const end = start + this.previewPageSize
      return this.previewData.slice(start, end)
    },

    // 预览数据总页数
    previewTotalPages() {
      return Math.ceil((this.previewData.length || 0) / this.previewPageSize)
    },
    // 是否有选择文件
    hasFile() {
      return this.excelFile !== null
    },
    // 是否可以导入（有选中字段）
    canImport() {
      return this.selectedFields.length > 0 && this.showDataPreview
    }
  }
  , methods: {
    handleSizeChange(a, b) {
      // this.pageSize = val; // 改变每页显示的条数
      // this.currentPage = 1; // 重置当前页为第一页
      this.currentPage = b, // 当前页码
          this.pageSize = a // 每页显示条数
      this.handleChange(this.well_id);
    },
    handleCurrentChange(c) {
      // this.currentPage = val; // 改变当前页码
      console.log('当前页码:', c);
      this.currentPage = c // 当前页码
      this.handleChange(this.well_id);
      // getZndbList(this.currentPage)
    },
    // 处理预览数据分页变化
    handlePreviewPageChange(page) {
      this.previewCurrentPage = page
    },
    // 处理文件变化
    handleFileChange(file, fileList) {
      this.excelFileList = fileList
      this.excelFile = file.raw
    },
    // 解析Excel文件（上传到后端解析）
    parseExcelFile() {
      if (!this.excelFile) {
        this.$message.warning('请选择Excel文件')
        return
      }

      const formData = new FormData()
      formData.append('file', this.excelFile);
      //添加第二个参数：选中的井的名字
      formData.append('well_id', this.well_id);

      this.loading = true
      this.previewCurrentPage = 1 // 重置预览分页

      // 调用后端解析接口
      api.post('/fcData/importFile', formData,).then(response => {
        const result = response.data
        console.log("解析数据", result);
        if (result.code === 0) {
          const fcListData = result.fcListData || {}
          //储存原数据
          this.originalData = fcListData

          //获取所有的字段名
          this.allFields = Object.keys(fcListData[0])

          console.log("所有的字段", this.allFields);
          this.previewData = fcListData
          this.totalRecords = this.previewData.length

          // 初始化字段选择
          this.selectedFields = [...this.allFields]
          this.selectAllFields = true
          this.isIndeterminate = false

          this.showDataPreview = true
        } else {
          this.$message.error('解析失败：' + result.msg)
        }
      }).catch(error => {
        console.error('解析文件失败:', error)
        this.$message.error('解析文件失败：' + (error.response?.data?.message || error.message))
      }).finally(() => {
        this.loading = false
      })
    },
    // 处理全选
    handleSelectAll(val) {
      this.selectedFields = val ? [...this.allFields] : []
      this.isIndeterminate = false
    },

    // 处理字段选择变化
    handleFieldChange(values) {
      const checkedCount = values.length
      this.selectAllFields = checkedCount === this.allFields.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allFields.length
    },
    // 获取所有井的数据
    getWellInfoList() {
      const map = {
        currentPage: 0,
        keyword: "",
      }
      api.post("/wellInfo/getWellInfoList", map).then(res => {
        this.wellList = res.data.wellInfoList;
        console.log(res);
      })
    },
    // 确认导入
    confirmImport() {
      if (this.selectedFields.length === 0) {
        this.$message.warning('请至少选择一个导入字段')
        return
      }

      // 直接从原始数据中筛选选中的字段
      const importData = this.originalData.map(item => {
        const filteredItem = {}
        this.selectedFields.forEach(field => {
          filteredItem[field] = item[field]
        })
        return filteredItem
      })

      console.log("导入的数据", importData)
      const map = {
        wellId: this.well_id,
        fcListData: importData
      }

      // 调用导入接口
      api.post('/fcData/importFcData', map).then(response => {
        const result = response.data
        if (result.code === 0) {
          this.$message.success(`导入成功`)
          this.cancelImport()
          // 刷新当前页面
          this.handleChange(this.well_id);
        } else {
          this.$message.error('导入失败：' + result.message)
        }
      }).catch(error => {
        console.error('导入数据失败:', error)
        this.$message.error('导入失败：' + (error.response?.data?.message || error.message))
      }).finally(() => {
        this.loading = false
      })
    },
    // 取消导入
    cancelImport() {
      this.showImportDialog = false
      this.excelFileList = []
      this.excelFile = null
      this.showDataPreview = false
      this.allFields = []
      this.previewData = []
      this.totalRecords = 0
      this.selectedFields = []
      this.selectAllFields = false
      this.isIndeterminate = false
      this.loading = false
      this.previewCurrentPage = 1
    },
    // 下拉框的改变事件
    handleChange(val) {
      console.log(val);
      this.well_id = val;
      const map = {
        wellId: this.well_id,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
      }
      //发送请求
      api.post("/fcData/getFcData", map).then(res => {
        this.fileList = res.data.fcListData;
        this.total = res.data.total;
        console.log("获取到的数据", res);
      }).catch(err => {
        console.log(err);
      })
    },
    //数据预处理
    handleData() {
      // let formData = new FormData();
      // formData.append("wellId", this.well_id);
      // api.post("/importFile/prepData", formData).then(res => {
      //   if (res.data.code = 0) {
      //     //弹出消息提示框
      //     this.$message({
      //       message: '数据预处理成功',
      //       type: "success",
      //     })
      //     //刷新页面
      //     this.handleChange(this.well_id)
      //   }
      // }).catch(err => {
      //   console.log(err);
      // })
    },
    getCellClass(value) {
      if (value === -9999 || value === -999.25) {
        return 'orange-cell';
      } else if (value === 0.001) {
        return 'green-cell';
      }
      return '';
    }
  }, created() {
    this.getWellInfoList();
  }
})
</script>

<style scoped lang="less">
.container {
  padding: 20px; /* 添加内边距，让内容不紧贴边缘 */
  display: flex;
  flex-direction: column;
  justify-content: flex-start; /* 确保内容始终从顶部开始排列 */
  align-items: flex-start; /* 左对齐所有子元素 */
}

.top-bar {
  display: flex;
  align-items: center;
}

.table-container {
  height: 600px; /* 设置表格容器的高度 */
  overflow-y: auto; /* 允许垂直滚动 */
  width: 100%;
}

.upload-demo {
  margin-bottom: 20px; /* 与表格保持一定距离 */
}
.loading-container {
  text-align: center;
  padding: 30px;
}

.preview-container {
  margin-top: 15px;
}

.field-selection {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 10px;
}

.fields-group {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px 20px;
  //max-height: 100px; /* 限制字段选择区域高度 */
  //overflow-y: auto;  /* 字段过多时允许滚动 */
}
.preview-info {
  margin-top: 10px;
  text-align: right;
  color: #606266;
  font-size: 12px;
}
.orange-cell {
  background-color: rgba(255, 215, 0, 0.2); // 橙黄色
  display: inline-block;
  width: 100%;
  padding: 2px;
}

.green-cell {
  background-color: rgba(144, 238, 144, 0.2); // 浅绿色
  display: inline-block;
  width: 100%;
  padding: 2px;
}
</style>